<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="编号" prop="devId">
        <el-input
          v-model="queryParams.devId"
          placeholder="请输入编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否在线" prop="online">
        <el-select v-model="queryParams.online" placeholder="请选择是否在线" clearable>
          <el-option
            v-for="dict in dict.type.iot_communication"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否故障" prop="isFault">
        <el-select v-model="queryParams.isFault" placeholder="请选择是否故障" clearable>
          <el-option
            v-for="dict in dict.type.iot_device_state"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>

        <el-form-item label="项目"  prop="projectName" >
          <el-select
            v-model="queryParams.projectId"
            placeholder="请选择项目"
            clearable
            @keyup.enter.native="handleQuery"
          >
            <el-option v-for="item in projectList"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产品"  prop="productName" >
          <el-select
            v-model="queryParams.productId"
            placeholder="请选择产品"
            clearable
            @keyup.enter.native="handleQuery"
          >
            <el-option
              v-for="item in productList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>


      </el-form-item>


    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['iot:device:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['iot:device:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['iot:device:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['iot:device:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="deviceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="编号" align="center" prop="devId" />
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column label="是否在线" align="center" prop="online">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.iot_communication" :value="scope.row.online"/>
        </template>
      </el-table-column>
      <el-table-column label="是否故障" align="center" prop="isFault">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.iot_device_state" :value="scope.row.isFault"/>
        </template>
      </el-table-column>
      <el-table-column label="项目" align="center" prop="projectName" />
      <el-table-column label="产品" align="center" prop="productName" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="创建者" align="center" prop="creator" />
      <el-table-column label="创建时间" align="center" prop="createDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['iot:device:edit']"
          >修改</el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleMutual(scope.row)"
          >交互</el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['iot:device:remove']"
          >删除</el-button>


        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改设备对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="编号" prop="devId">
          <el-input v-model="form.devId" placeholder="请输入编号" />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="是否在线" prop="online">
          <el-select v-model="form.online" placeholder="请选择是否在线">
            <el-option
              v-for="dict in dict.type.iot_communication"
              :key="dict.value"
              :label="dict.label"
:value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否故障" prop="isFault">
          <el-select v-model="form.isFault" placeholder="请选择是否故障">
            <el-option
              v-for="dict in dict.type.iot_device_state"
              :key="dict.value"
              :label="dict.label"
:value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="项目"  prop="projectName" >
          <el-select
            v-model="form.projectId"
            placeholder="请选择项目"
            clearable
            @keyup.enter.native="handleQuery"
          >
            <el-option v-for="item in projectList"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产品"  prop="productName" >
          <el-select
            v-model="form.productId"
            placeholder="请选择产品"
            clearable
            @keyup.enter.native="handleQuery"
          >
            <el-option
              v-for="item in productList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <el-dialog :title="title" :visible.sync="devCmdExplainOpen" width="500px" append-to-body>
      <el-form  :model="devCmdVo" :rules="rules" label-width="80px">
        <el-form-item label="编号" prop="devId">
          <el-input v-model="devCmdVo.devId" placeholder="请输入编号" disabled = "true" />
        </el-form-item>

        <el-form-item label="操作指令" prop="cmdId">
          <el-select v-model="devCmdVo.cmdId" placeholder="请选择需要操作的指令" @change="inPassingCmdExplainJson">
            <el-option
              v-for="dict in devCmdExplainVo.cmdExplainVos"
              :key="dict.cmdId"
              :label="dict.cmdName"
              :value="parseInt(dict.cmdId)"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="交互数据" prop="data">
          <el-input type="textarea" :rows = "10" v-model="devCmdVo.data" placeholder="请输入json数据" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitDevCmd">发 送</el-button>
        <el-button @click="cmdTranslate">转 换</el-button>
        <el-button @click="cancelDevCmd">取 消</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import { listDevice, getDevice, delDevice, addDevice, updateDevice,
  getDeviceCmdExplain, deviceOperate, deviceCmdTranslate } from "@/api/iot/device";

export default {
  name: "Device",
  dicts: ['iot_communication', 'iot_device_state'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备表格数据
      deviceList: [],
      //项目列表
      projectList:[],
      //协议列表
      frameList:[],
      //产品列表
      productList:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否弹出指令的解释文档
      devCmdExplainOpen: false,
      // 设备指令解释器
      devCmdExplainVo : {
        devId : null,
        cmdExplainVos:[],
      },
      cmdExplainVo : {
        cmdId : null,
        cmdName: null,
        cmdJson : null,
      },
      devCmdVo: {
        devId : null,
        cmdId : null,
        data : null,
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        devId: null,
        name: null,
        online: null,
        isFault: null,
        projectId: null,
        productId: null,
        frameId: null,
        projectName: null,
        productName: null,
        frameName: null,
        creator: null,
        createDate: null,
        updater: null,
        updateDate: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询设备列表 */
    getList() {
      this.loading = true;
      listDevice(this.queryParams).then(response => {
        this.deviceList = response.rows;
        this.projectList = response.projectList;
        this.productList = response.productList;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        devId: null,
        name: null,
        online: null,
        isFault: null,
        projectId: null,
        productId: null,
        frameId: null,
        projectName: null,
        productName: null,
        remark: null,
        creator: null,
        createDate: null,
        updater: null,
        updateDate: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加设备";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getDevice(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改设备";
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateDevice(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDevice(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除设备编号为"' + ids + '"的数据项？').then(function() {
        return delDevice(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('iot/device/export', {
        ...this.queryParams
      }, `device_${new Date().getTime()}.xlsx`)
    },
    /** 涉及交互 */
    handleMutual(row){
      const id =  row.id;
      getDeviceCmdExplain(id).then( response => {
        this.devCmdExplainVo = response.data;
        this.devCmdExplainOpen = true;
        this.devCmdVo.cmdId = response.data.cmdExplainVos[0].cmdId;
        this.devCmdVo.devId = row.devId;
        this.devCmdVo.data = JSON.stringify(response.data.cmdExplainVos[0].cmdJson,null,'\t');
      })
    },
    /** 带出 cmd解释的json数据 */
    inPassingCmdExplainJson(){
      for(let i = 0; i < this.devCmdExplainVo.cmdExplainVos.length; i++){
        this.cmdExplainVo = this.devCmdExplainVo.cmdExplainVos[i];
        if(this.devCmdVo.cmdId == this.cmdExplainVo.cmdId) {
          this.devCmdVo.data = JSON.stringify(this.cmdExplainVo.cmdJson,null,'\t');
        }
      }
    },
    /**
     * 提交设备指令数据
     */
    submitDevCmd(){
      deviceOperate(this.devCmdVo.data).then(response => {
        let str = JSON.stringify(response.data,null,'\t');
        alert(str);
      })
    },
    /** 指令转换 */
    cmdTranslate() {
      deviceCmdTranslate(this.devCmdVo.data).then(response => {
        let hexFrame = response.hexFrame;
        alert(hexFrame)
      })

    },
    /** 结束设备指令 */
    cancelDevCmd (){
      this.open = false;
      this.devCmdVo = null;
    },
  },


};
</script>
